<?php
require_once 'database21.php';

class User extends Database {
    public function register($username, $password) {
        try {
            $stmt = $this->conn->prepare("SELECT * FROM userinfo WHERE username = :username");
            $stmt->execute([':username' => $username]);

            if ($stmt->rowCount() > 0) {
                throw new Exception("用户名已存在");
            }

            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $this->conn->prepare("INSERT INTO userinfo (username, password) VALUES (:username, :password)");
            $stmt->execute([':username' => $username, ':password' => $hashedPassword]);

            return $this->conn->lastInsertId();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function login($username, $password) {
        try {
            $stmt = $this->conn->prepare("SELECT * FROM userinfo WHERE username = :username");
            $stmt->execute([':username' => $username]);

            $user = $stmt->fetch();

            if (!$user || !password_verify($password, $user['password'])) {
                throw new Exception("用户名或密码错误");
            }

            return $user;
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }
}
?>